package com.dmgn.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dmgn.bean.Archives;
import com.dmgn.bean.Patent;
import com.dmgn.bean.Project;
import com.dmgn.bean.RequestParam;
import com.dmgn.bean.ResponseParam;
import com.dmgn.bean.Thesis;
import com.dmgn.bean.Work;
import com.dmgn.service.IArchivesService;
import com.dmgn.service.ICSVConverter;
import com.dmgn.serviceimpl.CSVImportPatentImpl;
import com.dmgn.serviceimpl.CSVImportProjectImpl;
import com.dmgn.serviceimpl.CSVImportThesisImpl;
import com.dmgn.serviceimpl.CSVImportWorkImpl;
import com.dmgn.serviceimpl.PatentServiceImpl;
import com.dmgn.serviceimpl.ProjectServiceImpl;
import com.dmgn.serviceimpl.ThesisServiceImpl;
import com.dmgn.serviceimpl.WorkServiceImpl;
import com.dmgn.util.BaseAction;
import com.dmgn.util.ChangeFileName;
import com.dmgn.util.CreatFile;
import com.dmgn.util.UploadFile;

public class ArchivesAction extends BaseAction{

	/**
	 * @Fields serialVersionUID : TODO
	 */
	private static final long serialVersionUID = 1L;
	
	private Archives archives;
	private RequestParam requestParam;
	private ResponseParam responseParam;
	
	private List<Archives> archivesList = new ArrayList<Archives>();
	
	private IArchivesService archivesService;

	public void chooseArchives(int type){
		switch(type){
		case 0:{
			archivesService = new ThesisServiceImpl();
			break;
		}
		case 1:{
			archivesService = new PatentServiceImpl();
			break;
		}
		case 2:{
			archivesService = new ProjectServiceImpl();
			break;
		}
		case 3:{
			archivesService = new WorkServiceImpl();
			break;
		}
		default:
			break;
		}
	}
	
	/**
	 * 获取档案
	 * param：requestParam
	 * 
	 * @return
	 */
	public String getArchivesArray(){
		
		String[] idArr = requestParam.getLabelIdStr().split(",");
		String idStr = "";
		for(String temp:idArr){
			idStr += "%"+"#"+temp+"#";
		}
		idStr += "%";
		requestParam.setLabelIdStr(idStr);
		
		chooseArchives(requestParam.getType());
		String employeenumber = null;
		if(session.get("role").equals(0))
			employeenumber = session.get("employeenumber").toString();
		archivesList = archivesService.findArchives(requestParam.getPageNo(), requestParam.getQueryStr(), requestParam.getLabelIdStr(),employeenumber);
		responseParam = new ResponseParam();
		responseParam.setTotalNum(archivesService.getTotalNum(requestParam.getQueryStr(), requestParam.getLabelIdStr(),employeenumber));
		return SUCCESS;
	}
	
	/**
	 * 档案查看
	 * param：requestParam
	 * 
	 * @return
	 */
	public String getArchivesInfo(){
		chooseArchives(requestParam.getType());
		archives = archivesService.findSingleArchives(Integer.parseInt(requestParam.getArchivesIdStr()));
		return SUCCESS;
	}
	
	/**
	 * 批量导入档案
	 * param：requestParam
	 * 
	 * @return
	 */
	public String batchImportArchives(){
		String fileName = "";
		ChangeFileName cf = new ChangeFileName();
		UploadFile uf = new UploadFile();
		
		String excelFileName = requestParam.getExcelFileName();
		String excelContentType = requestParam.getExcelContentType();
		File excel = requestParam.getExcel();
		
		excelFileName="\\"+cf.changeFileName(excelFileName);
		fileName = uf.upload(excel, excelFileName);
		
		ICSVConverter csv = null;
		
		switch(requestParam.getType()){
		case 0:{
			csv = new CSVImportThesisImpl();
			break;
		}
		case 1:{
			csv = new CSVImportPatentImpl();
			break;
		}
		case 2:{
			csv = new CSVImportProjectImpl();
			break;
		}
		case 3:{
			csv = new CSVImportWorkImpl();
			break;
		}
		default:
			break;
	}
		
		String result="";
		
		result= csv.batchImport(fileName);
		
		if(result != ""){
			responseParam.setMessage(result);
		}
		return SUCCESS;
	}

	/**
	 * 审核档案
	 * param：requestParam
	 * 
	 * @return
	 */
	public String auditArchives(){
		responseParam = new ResponseParam();
		if(session.get("role").equals(2)){
			chooseArchives(requestParam.getType());
			if(archivesService.updateAuditStatus(requestParam.getArchivesIdStr(), requestParam.getStatus())){
				responseParam.setMessage("审核成功");
				return SUCCESS;
			}
			else{
				responseParam.setMessage("审核失败");
				return ERROR;
			}
		}
		else{
			responseParam.setMessage("无权限");
			return ERROR;
		}
		
	}
	
	/**
	 * 删除档案
	 * param：requestParam
	 * 
	 * @return
	 */
	public String deleteArchives(){
		responseParam = new ResponseParam();
		chooseArchives(requestParam.getType());
		if(archivesService.updateStatus(requestParam.getArchivesIdStr(), -1)){
			responseParam.setMessage("删除成功");
			return SUCCESS;
		}
		else{
			responseParam.setMessage("删除失败");
			return ERROR;
		}
	}
	
	/**
	 * 档案分类
	 * param：requestParam
	 * 
	 * @return
	 */
	public String classifyArchives(){
		responseParam = new ResponseParam();
		
		if(requestParam.getLabelIdStr()!=""){
			String[] idArr = requestParam.getLabelIdStr().split(",");
			String idStr = "";
			for(String temp:idArr){
				idStr += "#"+temp+"#"+",";
			}
			idStr = idStr.substring(0, idStr.length()-1);
			requestParam.setLabelIdStr(idStr);
		}
		
		chooseArchives(requestParam.getType());
		if(archivesService.updateLabel(requestParam.getArchivesIdStr(), requestParam.getLabelIdStr())){
			responseParam.setMessage("分类成功");
			return SUCCESS;
		}
		else{
			responseParam.setMessage("分类失败");
			return ERROR;
		}
	}
	
	/**
	 * 档案附加资料上传
	 * param：requestParam
	 * 
	 * @return
	 */
	public String uploadDocument() throws Exception{
		
		chooseArchives(requestParam.getType());
		archives = archivesService.findSingleArchives(Integer.parseInt(requestParam.getArchivesIdStr()));
		
		String id = requestParam.getArchivesIdStr();
		String file = null;
		
		switch(requestParam.getType()){
		case 0:{
			Thesis thesis = (Thesis)archives;
			file = thesis.getFile();
//			webnumber = thesis.getWebnumber();
			break;
		}
		case 1:{
			Patent patent = (Patent)archives;
			file = patent.getFile();
//			webnumber = patent.getWebnumber();
			break;
		}
		case 2:{
			Project project = (Project)archives;
			file = project.getFile();
//			webnumber = project.getWebnumber();
			break;
		}
		case 3:{
			Work work = (Work)archives;
			file = work.getFile();
//			webnumber = work.getWebnumber();
			break;
		}
		default:
			break;
		}
		
		if (file==null)
			file="";
		
		SimpleDateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
		String dateString = df.format(new Date());
		
		//创建文件夹
		String documentPath[] =new String[2];
		documentPath[0] = "documentmgn";
		documentPath[1] = String.valueOf(requestParam.getType());
		documentPath[2] = id;
		CreatFile cf=new CreatFile();
		cf.CreatFileByList(documentPath);
		
		//获得路径
		String p=System.getProperty("user.dir");	
		String savepath= p.substring(0, p.lastIndexOf("\\"))+"\\documentmgn\\"+String.valueOf(requestParam.getType())+"\\"+id;
		
		responseParam = new ResponseParam();
		
		//上传文件
		if (requestParam.getUpload()!=null){
			File[] files = requestParam.getUpload();
			String[] uploadFileName = requestParam.getUploadFileName();
			String[] uploadContentType = requestParam.getUploadContentType();
			for(int i=0;i<files.length;i++)
			{
				String newName = uploadFileName[i].substring(0,uploadFileName[i].lastIndexOf(".")) + "-" + dateString + uploadFileName[i].substring(uploadFileName[i].lastIndexOf("."));
				
				FileOutputStream fos = new FileOutputStream(savepath+"\\"+newName);
				FileInputStream fis = new FileInputStream(files[i]);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = fis.read(buffer))>0)
				{
					fos.write(buffer, 0, len);
				}
				fos.close();
				uploadFileName[i]=newName;
				
				if (file.length() != 0){
					file += "|";
				}
				
				if (i!=files.length-1)
					file+=uploadFileName[i];
				else
					file+=uploadFileName[i];
			}
			
//			archives.setaPath(path);
			archivesService.updateFile(requestParam.getArchivesIdStr(), file);
			responseParam.setMessage("附件上传成功。");
			return SUCCESS;
		}
		else{
			responseParam.setMessage("附件上传失败。");
			return ERROR;
		}
	}
	
	/**
	 * 档案附加资料下载
	 * param：requestParam
	 * 
	 * @return
	 */
	public String downloadArchives(){
		System.out.println("download-->");
		return SUCCESS;
	}
	public InputStream getDownloadFile() throws Exception{ 
		
		String fileFileName = requestParam.getFileFileName();
		
		System.out.println("getDownloadFile-->");
		System.out.println(fileFileName);
		
		File file = new File("../documentmgn/"+requestParam.getType()+"/"+requestParam.getArchivesIdStr()+"/"+fileFileName);  
         
        InputStream inStream = null;           
        inStream = new FileInputStream(file);
        
//        fileFileName = new String(fileFileName.getBytes(), "ISO8859-1");           
        return inStream;
   	}
	
	public Archives getArchives() {
		return archives;
	}

	public void setArchives(Archives archives) {
		this.archives = archives;
	}

	public RequestParam getRequestParam() {
		return requestParam;
	}

	public void setRequestParam(RequestParam requestParam) {
		this.requestParam = requestParam;
	}

	public ResponseParam getResponseParam() {
		return responseParam;
	}

	public void setResponseParam(ResponseParam responseParam) {
		this.responseParam = responseParam;
	}

	public List<Archives> getArchivesList() {
		return archivesList;
	}

	public void setArchivesList(List<Archives> archivesList) {
		this.archivesList = archivesList;
	}

	public IArchivesService getArchivesService() {
		return archivesService;
	}

	public void setArchivesService(IArchivesService archivesService) {
		this.archivesService = archivesService;
	}

}
